import React, { useEffect, useRef, useState, useContext } from 'react';
import { Col, Row, Card, message } from 'antd';
import { useTranslation } from 'react-i18next';
import * as echarts from 'echarts';
import axios from 'axios';
import { AuthContext } from '../../contexts/AuthContext';
import { useNavigate } from 'react-router-dom';

const LittleHeader = () => {
    const { t } = useTranslation();
    const { token } = useContext(AuthContext);
    const vulnChartRef = useRef(null);
    const riskChartRef = useRef(null);
    const [packageCount, setPackageCount] = useState(0);
    const [loading, setLoading] = useState(false);
    const chartInstances = useRef({});
    const navigate = useNavigate(); 

    const vulnData = [10, 10000, 20000, 30000, 40000, 553171];
    const vulnCount = vulnData[vulnData.length - 1];

    // 获取图表配置
    const getChartOption = (data, color) => ({
        grid: { top: 0, right: 0, bottom: 0, left: 0 },
        xAxis: { show: false },
        yAxis: { show: false },
        series: [{
            type: 'line',
            data: data,
            symbol: 'none',
            lineStyle: {
                color: data[data.length - 1] > 0 ? color : '#d9d9d9',
                width: 2
            },
            areaStyle: data[data.length - 1] > 0 ? {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: `${color}33` },
                    { offset: 1, color: `${color}00` }
                ])
            } : undefined
        }]
    });

    // 初始化或更新图表
    const initChart = (ref, data, color, chartKey) => {
        if (!ref.current) return;

        // 销毁现有实例
        if (chartInstances.current[chartKey]) {
            chartInstances.current[chartKey].dispose();
        }

        const chart = echarts.init(ref.current);
        chartInstances.current[chartKey] = chart;

        const resizeObserver = new ResizeObserver(() => {
            chart.resize();
        });
        resizeObserver.observe(ref.current);

        chart.setOption(getChartOption(data, color));
    };
    const fetchPackageCount = async () => {
        try {
            const response = await axios.post('/api/v1/pkg/query',
                { page: 1, size: 1000 },
                {
                    headers: {
                        'Authorization': token,
                    }
                }
            );

            if (response.data?.code === 0) {
                const packages = response.data.data?.list || response.data.data || [];
                setPackageCount(packages.length);

                // 生成风险数据趋势
                const fixedSequence = [1, 2, 0, 0, 10];
                const newRiskData = Array(6).fill(0).map((_, i) =>
                    i === 5 ? packages.length : fixedSequence[i]
                );

                initChart(riskChartRef, newRiskData, '#1890ff', 'riskChart');
                initChart(vulnChartRef, vulnData, '#ff4d4f', 'vulnChart');
            } else if ([1003, 1001, 1002].includes(response.data.code)) {
                message.error(t('Token失效，请重新登录'))
                localStorage.removeItem('username');
                localStorage.removeItem('enc_token');
                localStorage.removeItem('privilege_level');
                navigate('/login');
            } else {
                message.error( t('失败'));
            }
        } catch (error) {
            console.error('获取软件包数据失败:', error);
            message.error(t('失败'));
            if (error.response) {
                console.error('响应数据:', error.response.data);
            } else if (error.request) {
                console.error('请求数据:', error.request);
            }
        }
    };

    useEffect(() => {
        if (token) {
            fetchPackageCount();
        }

        return () => {
            // 组件卸载时销毁所有图表实例
            Object.values(chartInstances.current).forEach(chart => {
                if (chart && !chart.isDisposed()) {
                    chart.dispose();
                }
            });
        };
    }, [token]);

    return (
        <Row gutter={16}>
            <Col span={12}>
                <Card
                    title={t("公共漏洞数量")}
                    variant="borderless"
                >
                    <div style={{ fontSize: 24, fontWeight: 'bold' }}>{vulnCount}</div>
                    <div ref={vulnChartRef} style={{ height: 50, marginTop: 8, width: '100%' }} />
                </Card>
            </Col>
            <Col span={12}>
                <Card
                    title={t("面临风险的项目")}
                    variant="borderless"
                    loading={loading}
                >
                    <div style={{ fontSize: 24, fontWeight: 'bold' }}>{packageCount}</div>
                    <div ref={riskChartRef} style={{ height: 50, marginTop: 8, width: '100%' }} />
                </Card>
            </Col>
        </Row>
    );
};

export default LittleHeader;